/**
 * 
 */
package com.system.core.dingtalk;

import java.net.URLEncoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;

import lombok.experimental.UtilityClass;

/**
 * <p>paycore-common-util项目新建类DingTalkUtil，请输入类描述</p>
 * @author jlcon
 * @version DingTalkUtil.java, v1.0 2020.10.29 15:30:32
 */
@UtilityClass
public class DingTalkUtil {

	public String getSign(Long timestamp,String secret) {
		try {
			String stringToSign = timestamp + "\n" + secret;
			Mac mac = Mac.getInstance("HmacSHA256");
			mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
			byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
			String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
			return sign;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public String getAccessToken(String appKey,String appSecret) throws Exception {
		DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
		OapiGettokenRequest request = new OapiGettokenRequest();
		request.setAppkey(appKey);
		request.setAppsecret(appSecret);
		request.setHttpMethod("GET");
		OapiGettokenResponse response = client.execute(request);
		return response.getAccessToken();
	}
}
